/************************************************************************
<4loco-aprs.  This program connects to a specified APRS server and displays
    the information on a map. It's being developed using QT Creator. The project
    began in February and version 1 should be released in April. For more
    information go to http://code.google.com/p/4loco-aprs/>

    Copyright (C) <2011>  <Kyle Roden, Glen Riden, Aaron Smith, Alisa Emerich>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "purgethread.h"


PurgeThread::PurgeThread(QSqlDatabase &purgeDB, QSqlDatabase &purgeTimeDB)
{
    /*purgeDatabase = QSqlDatabase::addDatabase("QSQLITE", "purge_packets");
    purgeDatabase.setDatabaseName("../packets_database.db");
    purgeTimeDatabase = QSqlDatabase::addDatabase("QSQLITE", "purge_time");
    purgeTimeDatabase.setDatabaseName("../config.db");

    if (!purgeDatabase.open())
        qDebug() << purgeDatabase.lastError();
    if (!purgeTimeDatabase.open())
        qDebug() << purgeTimeDatabase.lastError();
*/

    purgeDatabase = &purgeDB;
    purgeTimeDatabase = &purgeTimeDB;
}

PurgeThread::~PurgeThread()
{
 //  this->quit();
}

void PurgeThread::run()
{
    QSqlQuery deleteQuery(*purgeDatabase);
    QSqlQuery purgeQuery(*purgeDatabase);
    QSqlQuery timeQuery(*purgeTimeDatabase);

    while(true)
    {
        QThread::sleep(5); // run the thread every 5 seconds.




        if(!(timeQuery.exec("SELECT * FROM timing")))
          qDebug()<<timeQuery.lastError()<<"error in purge thread run select * from timing";
        while (timeQuery.next())
            purgeTimeSetting = timeQuery.value(1).toString();

        if (purgeTimeSetting != "NEVER")
            hasPurgeTime = true;
        else
            hasPurgeTime = false;


        if (hasPurgeTime)
        {
            // This branch has to calculate the current time and calculate the purge time from the database packet.
            curr_yr = QDateTime::currentDateTime().toString("yyyy").toInt();
            curr_mth = QDateTime::currentDateTime().toString("MM").toInt();
            curr_day = QDateTime::currentDateTime().toString("dd").toInt();
            curr_hr = QDateTime::currentDateTime().toString("hh").toInt();
            curr_min = QDateTime::currentDateTime().toString("mm").toInt();
            curr_sec = QDateTime::currentDateTime().toString("ss").toInt();


            if(!(purgeQuery.exec("SELECT * FROM packets;")))
              qDebug()<<purgeQuery.lastError()<<"error select * from packets";
            while (purgeQuery.next())
            {
                importedTime = QDateTime::fromString(purgeQuery.value(1).toString(), "yyyyMMddhhmmss");
                raw_copy = purgeQuery.value(1).toString();

                purge_yr = importedTime.date().toString("yyyy").toInt();
                purge_mth = importedTime.date().toString("MM").toInt();
                purge_day = importedTime.date().toString("dd").toInt();
                purge_hr = importedTime.time().toString("hh").toInt();
                purge_min = importedTime.time().toString("mm").toInt();
                purge_sec = importedTime.time().toString("ss").toInt();


                if (purgeTimeSetting.toInt() >= (24*60))
                {
                    // purge time is in days
                    purge_day += (purgeTimeSetting.toInt()/(24*60));
                    if (purge_day > 31 && (purge_mth == 1 || purge_mth == 3 || purge_mth == 5 || purge_mth == 7 || purge_mth == 8 || purge_mth == 10 || purge_mth == 12))
                    {
                        // we were in 31 day months
                        purge_day -= 31;
                        purge_mth++;

                        if (purge_mth > 12)
                        {
                            purge_mth = 1;
                            purge_yr++;
                        }
                    }
                    else if (purge_day > 30 && (purge_mth == 4 || purge_mth == 6 || purge_mth == 9 || purge_mth == 11))
                    {
                        purge_day -= 30;
                        purge_mth++;
                    }
                    else if (purge_day > 28 && purge_mth == 2)
                    {
                        purge_day -= 28;
                        purge_mth++;
                    }
                }
                else
                {
                    // purge time is in hours
                    purge_hr += (purgeTimeSetting.toInt()/60);

                    if (purge_hr >= 24) // next day
                    {
                        purge_day++;
                        purge_hr-=24;
                        if (purge_day > 31 && (purge_mth == 1 || purge_mth == 3 || purge_mth == 5 || purge_mth == 7 || purge_mth == 8 || purge_mth == 10 || purge_mth == 12))
                        {
                            purge_mth++;
                            purge_day = 1;

                            if (purge_mth > 12)
                            {
                                purge_mth = 1;
                                purge_yr++;
                            }
                        }
                        else if (purge_day > 30 && (purge_mth == 4 || purge_mth == 6 || purge_mth == 9 || purge_mth == 11))
                        {
                            purge_mth++;
                            purge_day = 1;
                        }
                        else if (purge_day > 28 && purge_mth == 2)
                        {
                            purge_mth++;
                            purge_day = 1;
                        }
                    }
                    else
                    {
                        // same day
                        // do nothing
                    }
                }


                if (curr_yr > purge_yr)
                {
                    deleteQuery.prepare("DELETE FROM packets WHERE raw_timestamp = ?;");
                    deleteQuery.addBindValue(raw_copy);
                    deleteQuery.exec();
                    //qDebug() << "Data Purged.";
                }
                else if (curr_yr == purge_yr)
                {
                    if (curr_mth > purge_mth)
                    {
                        deleteQuery.prepare("DELETE FROM packets WHERE raw_timestamp = ?;");
                        deleteQuery.addBindValue(raw_copy);
                        deleteQuery.exec();
                        //qDebug() << "Data Purged.";
                    }
                    else if (curr_mth == purge_mth)
                    {
                        if (curr_day > purge_day)
                        {
                            deleteQuery.prepare("DELETE FROM packets WHERE raw_timestamp = ?;");
                            deleteQuery.addBindValue(raw_copy);
                            deleteQuery.exec();
                            //qDebug() << "Data Purged.";
                        }
                        else if (curr_day == purge_day)
                        {
                            if (curr_hr > purge_hr)
                            {
                                deleteQuery.prepare("DELETE FROM packets WHERE raw_timestamp = ?;");
                                deleteQuery.addBindValue(raw_copy);
                                deleteQuery.exec();
                                //qDebug() << "Data Purged.";
                            }
                            else if (curr_hr == purge_hr)
                            {
                                if (curr_min > purge_min)
                                {
                                    deleteQuery.prepare("DELETE FROM packets WHERE raw_timestamp = ?;");
                                    deleteQuery.addBindValue(raw_copy);
                                    deleteQuery.exec();
                                    //qDebug() << "Data Purged.";
                                }
                                else if (curr_min == purge_min)
                                {
                                    if (curr_sec >= purge_sec)
                                    {
                                        deleteQuery.prepare("DELETE FROM packets WHERE raw_timestamp = ?;");
                                        deleteQuery.addBindValue(raw_copy);
                                        deleteQuery.exec();
                                        //qDebug() << "Data Purged.";
                                    }
                                    else
                                        break;
                                }
                                else
                                    break;
                            }
                            else
                                break;
                        }
                        else
                            break;
                    }
                    else
                        break;
                }


            }

            //qDebug() << "Purge will be at:\t\t" << purge_yr << "-" << purge_mth << "-" << purge_day << "  " << purge_hr << ":" << purge_min << ":" << purge_sec;
            //qDebug() << "Current time is:\t\t" << curr_yr << "-" << curr_mth << "-" << curr_day << "  " << curr_hr << ":" << curr_min << ":" << curr_sec;

        }
        else
        {
            qDebug() << "Purge time is never.";
        }

    }
}
